home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / a_utils / perl / faq < prev    next >
Internet Message Format  |  1993-07-25  |  89KB

  1. Xref: ruuinf comp.lang.perl:16470 news.answers:9354 comp.answers:1104
  2. Path: ruuinf!sun4nl!mcsun!uunet!news.cnri.reston.va.us!newsserver.jvnc.net!howland.reston.ans.net!usc!cs.utexas.edu!asuvax!chnews!ornews.intel.com!news
  3. From: Randal L. Schwartz <merlyn@ora.com>
  4. Newsgroups: comp.lang.perl,news.answers,comp.answers
  5. Subject: comp.lang.perl FAQ (part 0 of 2)
  6. Followup-To: comp.lang.perl
  7. Date: 23 Jun 93 17:49:58 GMT
  8. Organization: Intel Corporation
  9. Lines: 46
  10. Approved: news-answers-request@MIT.Edu
  11. Message-ID: <merlyn.740857798.6721.1@kandinsky.intel.com>
  12. NNTP-Posting-Host: kandinsky.intel.com
  13.  
  14. Archive-name: perl-faq/part0
  15. Version: slightly modified from $Id: perl-intro,v 1.2 92/11/30 05:22:42 tchrist Exp Locker: tchrist $
  16.  
  17. [I have not changed anything here, but I haven't seen Tom post this in
  18. a while.  Maybe I'm going to become the FAQ maintainer... sigh.  For
  19. one thing, this FAQ doesn't address the Llama Book... a glaring
  20. oversight. :-)
  21.  
  22. This version is slightly updated from the one I posted a few days
  23. ago, as pointed out to me by Henk Penning <henkp@cs.ruu.nl>.
  24.  
  25. -- merlyn]
  26.  
  27. This article contains the table of contents to some of the most
  28. frequently asked questions in comp.lang.perl, a newsgroup devoted to
  29. the Perl programming language.  There are two pieces following 
  30. this, the general information questions in part1 and the largely
  31. technical opnes in part2.
  32.  
  33. They're all good questions, but they come up often enough that
  34. substantial net bandwidth can be saved by looking here first before
  35. asking.  Before posting a question, you really should consult the Perl
  36. man page; there's a lot of information packed in there.
  37.  
  38. Some questions in this group aren't really about Perl, but rather
  39. about system-specific issues.  You might also consult the Most
  40. Frequently Asked Questions list in comp.unix.questions for answers
  41. to this type of question.
  42.  
  43. The current version of perl is 4.035 (version 4, patchlevel 35).
  44. There haven't actually been 35 updates to perl4; rather, the context
  45. diffs posted to the net have been broken up into 35 news-digestable
  46. chunks.
  47.  
  48. This list is maintained by Tom Christiansen, and is archived on
  49. convex.com [130.168.1.1] in the file pub/perl/info/faq.  If you
  50. have any suggested additions or corrections to this article, please
  51. send them to Tom at either <tchrist@convex.com> or <convex!tchrist>.  
  52. Special thanks to Larry Wall for periodically reviewing this list for
  53. accuracy and especially for writing and releasing Perl in the first place.
  54.  
  55. print "Just another Perl hacker,"
  56. -- 
  57. Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
  58. merlyn@ora.com (semi-permanent) merlyn@kandinsky.intel.com (NEWSREADING ONLY)
  59. Quote: "Welcome to Portland, Oregon, home of the California Raisins!"
  60. Xref: ruuinf comp.lang.perl:16471 news.answers:9355 comp.answers:1105
  61. Path: ruuinf!sun4nl!mcsun!uunet!news.cnri.reston.va.us!newsserver.jvnc.net!howland.reston.ans.net!usc!cs.utexas.edu!asuvax!chnews!ornews.intel.com!news
  62. From: Randal L. Schwartz <merlyn@ora.com>
  63. Newsgroups: comp.lang.perl,news.answers,comp.answers
  64. Subject: comp.lang.perl FAQ (part 1 of 2)
  65. Followup-To: comp.lang.perl
  66. Date: 23 Jun 93 17:49:58 GMT
  67. Organization: Intel Corporation
  68. Lines: 866
  69. Approved: news-answers-request@MIT.Edu
  70. Message-ID: <merlyn.740857798.6721.2@kandinsky.intel.com>
  71. NNTP-Posting-Host: kandinsky.intel.com
  72.  
  73. Archive-name: perl-faq/part1
  74. Version: slightly modified from $Id: perl-info,v 1.2 92/11/30 05:22:33 tchrist Exp Locker: tchrist $
  75.  
  76. [I have not changed anything here, but I haven't seen Tom post this in
  77. a while.  Maybe I'm going to become the FAQ maintainer... sigh.  For
  78. one thing, this FAQ doesn't address the Llama Book... a glaring
  79. oversight. :-)
  80.  
  81. This version is slightly updated from the one I posted a few days
  82. ago, as pointed out to me by Henk Penning <henkp@cs.ruu.nl>.
  83.  
  84. -- merlyn@ora.com]
  85.  
  86. This posting contains answers to general information questions,
  87. mostly of a non-technical nature.  The following questions are 
  88. answered:
  89.  
  90. 1.1) What is Perl?
  91. 1.2) Is Perl hard to learn?
  92. 1.3) Should I program everything in Perl?
  93. 1.4) Where can I get Perl over the Internet?
  94. 1.5) Where can I get Perl via Email?
  95. 1.6) How can I get Perl via UUCP?
  96. 1.7) Where can I get more information on Perl?
  97. 1.8) Can people who aren't on USENET receive comp.lang.perl as a digest?
  98. 1.9) Are archives of comp.lang.perl available?
  99. 1.10) How do I get Perl to run on machine FOO?
  100. 1.11) Where can I get (info|inter|ora|sql|syb)perl?
  101. 1.12) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  102. 1.13) Where can I get undump for my machine?
  103. 1.14) Where can I get a perl-mode for emacs?
  104. 1.15) How can I use Perl interactively?
  105. 1.16) Is there a Perl shell? 
  106. 1.17) Is there a Perl profiler?
  107. 1.18) Is there a yacc for Perl?
  108. 1.19) How can I use curses with perl?
  109. 1.20) How can I use X with Perl?
  110. 1.21) What is perl4?  What is perl5?
  111. 1.22) How does Perl compare with languages like REXX or TCL?
  112. 1.23) Is it a Perl program or a Perl script?
  113. 1.24) What's the difference between "Perl" and "perl"?
  114. 1.25) What companies use or ship Perl?
  115. 1.26) Is there commercial, 3rd-party support for Perl?
  116. 1.27) Where can I get a list of the JAPH signature quotes?
  117. 1.28) Where can I get a list of Larry Wall witticisms?
  118. 1.29) Is there a pretty-printer for Perl?
  119.  
  120.  
  121. 1.1) What is Perl?
  122.  
  123.     A programming language, by Larry Wall <lwall@netlabs.com>.
  124.  
  125.     Here's the beginning of the description from the man page:
  126.  
  127.     Perl is an interpreted language optimized for scanning arbitrary text
  128.     files, extracting information from those text files, and printing reports
  129.     based on that information.  It's also a good language for many system
  130.     management tasks.  The language is intended to be practical (easy to use,
  131.     efficient, complete) rather than beautiful (tiny, elegant, minimal).  It
  132.     combines (in the author's opinion, anyway) some of the best features of C,
  133.     sed, awk, and sh, so people familiar with those languages should have
  134.     little difficulty with it.  (Language historians will also note some
  135.     vestiges of csh, Pascal, and even BASIC-PLUS.)  Expression syntax
  136.     corresponds quite closely to C expression syntax.  Unlike most Unix
  137.     utilities, Perl does not arbitrarily limit the size of your data--if
  138.     you've got the memory, Perl can slurp in your whole file as a single
  139.     string.  Recursion is of unlimited depth.  And the hash tables used by
  140.     associative arrays grow as necessary to prevent degraded performance.
  141.     Perl uses sophisticated pattern matching techniques to scan large amounts
  142.     of data very quickly.  Although optimized for scanning text, Perl can also
  143.     deal with binary data, and can make dbm files look like associative arrays
  144.     (where dbm is available).  Setuid Perl scripts are safer than C programs
  145.     through a dataflow tracing mechanism which prevents many stupid security
  146.     holes.  If you have a problem that would ordinarily use sed or awk or sh,
  147.     but it exceeds their capabilities or must run a little faster, and you
  148.     don't want to write the silly thing in C, then Perl may be for you.  There
  149.     are also translators to turn your sed and awk scripts into Perl scripts.
  150.  
  151.  
  152. 1.2) Is Perl hard to learn?
  153.     
  154.     No, Perl is easy to learn for two reasons.  
  155.    
  156.     The first reason is that most of Perl is derived from existing tools
  157.     and languages, ones that many people who turn to Perl already have
  158.     some familiarity with.  These include the C programming language, the
  159.     UNIX C library, the UNIX shell, sed, and awk.  If you already know
  160.     these somewhat, Perl should be very easy for you.
  161.  
  162.     The second reason that Perl is easy to learn is that you don't have to
  163.     know every thing there is to know about it in order to get good use
  164.     out of it.  In fact, just a very small subset, mostly borrowed from C,
  165.     the shell, and sed, will be enough for most tasks.  As you feel the
  166.     need or desire to use more sophisticated features (such as C
  167.     structures or networking), you can learn these as you go.  The
  168.     learning curve for Perl is not a steep one, especially if you have
  169.     the headstart of having a background in UNIX.  Rather, its learning
  170.     curve is gentle and gradual, but it *is* admittedly rather long.
  171.  
  172.     If you don't know C or UNIX at all, it'll be a steeper learning curve,
  173.     but what you then learn from Perl will carry over into other areas,
  174.     like using the C library, UNIX system call, regular expressions, and
  175.     associative arrays, just to name a few.  To know Perl is to know 
  176.     UNIX, and vice versa.
  177.  
  178.  
  179. 1.3) Should I program everything in Perl?
  180.  
  181.     Of course not.  You should choose the appropriate tool for the task at
  182.     hand.  While it's true that the answer to the question "Can I do (some
  183.     arbitrary task) in Perl?" is almost always "yes", that doesn't mean
  184.     this is necessarily a good thing to do.  For many people, Perl serves
  185.     as a great replacement for shell programming.  For a few people, it
  186.     also serves as a replacement for most of what they'd do in C.  But
  187.     for some things, Perl just isn't the optimal choice, such as tasks
  188.     requiring very complex data structures.
  189.  
  190.  
  191. 1.4) Where can I get Perl over the Internet?
  192.  
  193.     From any comp.sources.misc archive.   Initial sources  were posted to
  194.     Volume 18, Issues 19-54 at patchlevel 3.  The Patches 4-10 were posted
  195.     to Volume 20, Issues 56-62.  You can use the archie server
  196.     (see the alt.sources FAQ in news.answers) for ways to find these.
  197.  
  198.     These machines, at the very least, definitely have it available for
  199.     anonymous FTP:
  200.  
  201.     ftp.uu.net                137.39.1.2
  202.     archive.cis.ohio-state.edu      128.146.8.52
  203.     jpl-devvax.jpl.nasa.gov         128.149.1.143
  204.     ftp.netlabs.com         192.94.48.152
  205.     prep.ai.mit.edu            18.71.0.38
  206.     ftp.cs.ruu.nl            131.211.80.17  (Europe)
  207.  
  208.  
  209.  
  210.  
  211. 1.5) Where can I get Perl via Email?
  212.  
  213.     If you are in Europe, you might using the following site.  (I'm still
  214.     looking for a domestic site.) This information thanks to "Henk P.
  215.     Penning" <henkp@cs.ruu.nl>:  One automated fashion is as follows:
  216.  
  217.     Email: Send a message to 'mail-server@cs.ruu.nl' containing:
  218.      begin
  219.      path your_email_address
  220.      send help
  221.      send PERL/INDEX
  222.      end
  223.     The path-line may be omitted if your message contains a normal From:-line.
  224.     You will receive a help-file and an index of the directory that contains
  225.     the Perl stuff.
  226.  
  227.     If all else fails, mail to Larry usually suffices.
  228.  
  229.  
  230. 1.6) How can I get Perl via UUCP?
  231.  
  232.     You can get it from the site osu-cis; here is the appropriate info,
  233.     thanks to J Greely <jgreely@cis.ohio-state.edu> or <osu-cis!jgreely>.
  234.  
  235.     E-mail contact:
  236.         osu-cis!uucp
  237.     Get these two files first:
  238.         osu-cis!~/GNU.how-to-get.
  239.         osu-cis!~/ls-lR.Z
  240.     Current Perl distribution:
  241.         osu-cis!~/perl/4.0/kits@10/perl.kitXX.Z (XX=01-37)
  242.     How to reach osu-cis via uucp(L.sys/Systems file lines):
  243.     #
  244.     # Direct Trailblazer
  245.     #
  246.     osu-cis Any ACU 19200 1-614-292-5112 in:--in:--in: Uanon
  247.     #
  248.     # Direct V.32 (MNP 4)
  249.     # dead, dead, dead...sigh.
  250.     #
  251.     #osu-cis Any ACU 9600 1-614-292-1153 in:--in:--in: Uanon
  252.     #
  253.     # Micom port selector, at 1200, 2400, or 9600 bps.
  254.     # Replace ##'s below with 12, 24, or 96 (both speed and phone number).
  255.     #
  256.     osu-cis Any ACU ##00 1-614-292-31## "" \r\c Name? osu-cis nected \c GO \d\r\d\r\d\r in:--in:--in:
  257.      Uanon
  258.  
  259.     Modify as appropriate for your site, of course, to deal with your
  260.     local telephone system.  There are no limitations concerning the hours
  261.     of the day you may call.
  262.  
  263.     Another possibility is to use UUNET, although they charge you
  264.     for it.  You have been duly warned.  Here's the advert:
  265.  
  266.            Anonymous Access to UUNET's Source Archives
  267.  
  268.                  1-900-GOT-SRCS
  269.  
  270.      UUNET now provides access to its extensive collection of UNIX
  271.     related sources to non- subscribers.  By  calling  1-900-468-7727
  272.     and  using the login "uucp" with no password, anyone may uucp any
  273.     of UUNET's on line source collection.  Callers will be charged 40
  274.     cents  per  minute.   The charges will appear on their next tele-
  275.     phone bill.
  276.  
  277.      The  file  uunet!/info/help  contains  instructions.   The  file
  278.     uunet!/index//ls-lR.Z contains a complete list of the files available
  279.     and is updated daily.  Files ending in Z need to be uncompressed
  280.     before being used.   The file uunet!~/compress.tar is a tar
  281.     archive containing the C sources for the uncompress program.
  282.  
  283.      This service provides a  cost  effective  way  of  obtaining
  284.     current  releases  of sources without having to maintain accounts
  285.     with UUNET or some other service.  All modems  connected  to  the
  286.     900  number  are  Telebit T2500 modems.  These modems support all
  287.     standard modem speeds including PEP, V.32 (9600), V.22bis (2400),
  288.     Bell  212a  (1200), and Bell 103 (300).  Using PEP or V.32, a 1.5
  289.     megabyte file such as the GNU C compiler would cost $10  in  con-
  290.     nect  charges.   The  entire  55  megabyte X Window system V11 R4
  291.     would cost only $370 in connect time.  These costs are less  than
  292.     the  official  tape  distribution fees and they are available now
  293.     via modem.
  294.  
  295.               UUNET Communications Services
  296.            3110 Fairview Park Drive, Suite 570
  297.              Falls Church, VA 22042
  298.              +1 703 876 5050 (voice)
  299.               +1 703 876 5059 (fax)
  300.                 info@uunet.uu.net
  301.  
  302.  
  303.  
  304. 1.7) Where can I get more information on Perl?
  305.  
  306.     We'll cover five areas here: USENET (where you're probably reading
  307.     this), publications, the reference guide, examples on the Internet,
  308.     and Perl instructional courses.
  309.  
  310.     A.  USENET
  311.  
  312.     You should definitely read the USENET comp.lang.perl newsgroup or
  313.     mailing list for all sorts of discussions regarding the language,
  314.     bugs, features, history, humor, and trivia.  In this respect, it
  315.     functions both as a comp.lang.* style newsgroup and also as a user
  316.     group for the language; in fact, there's a mailing list called
  317.     ``perl-users'' that is bidirectionally gatewayed to the newsgroup; see
  318.     question #38 for details.  Larry Wall is a very frequent poster here,
  319.     as well as many (if not most) of the other seasoned Perl programmers.
  320.     It's the best place for the very latest information on Perl.
  321.  
  322.     B.  PUBLICATIONS
  323.  
  324.     If you've been dismayed by the ~80-page troffed Perl man page (or is
  325.     that man treatise?) you should look to ``the Camel Book'', written by
  326.     Larry and Randal L. Schwartz <merlyn@ora.com>, published as a Nutshell
  327.     Handbook by O'Reilly & Associates and entitled _Programming Perl_.
  328.     Besides serving as a reference guide for Perl, it also contains
  329.     tutorial material and is a great source of examples and cookbook
  330.     procedures, as well as wit and wisdom, tricks and traps, pranks and
  331.     pitfalls.  The code examples contained therein are available via
  332.     anonymous FTP from ftp.uu.net in
  333.     /published/oreilly/nutshell/perl/perl.tar.Z for your retrieval.
  334.     Corrections and additions to the book can be found in the Perl man
  335.     page right before the BUGS section under the heading ERRATA AND
  336.     ADDENDA.
  337.  
  338.     If you can't find the book in your local technical bookstore, the book
  339.     may be ordered directly from O'Reilly by calling 1-800-998-9938 if in
  340.     North America and 1-707-829-0515.  The book's ISBN is 0-937175-64-1.
  341.    
  342.     Autographed copies are *NO LONGER* available from TECHbooks --
  343.     you'll have to nab the authors in person if you want one.  Larry
  344.     routinely carries around a camel stamp for just such an occasion.
  345.  
  346.     Reasonably substantiated rumor has it that there will be another Perl
  347.     book out pretty soon, this one aimed more at beginners.  Look for it
  348.     from ORA towards the beginning of 93.
  349.  
  350.     Larry Wall has published a 3-part article on perl in Unix World
  351.     (August through October of 1991), and Rob Kolstad also had a 3-parter
  352.     in Unix Review (May through July of 1990).  Tom Christiansen also has
  353.     a brief overview article in the trade newsletter Unix Technology
  354.     Advisor from November of 1989.  You might also investigate "The Wisdom
  355.     of Perl" by Gordon Galligher from SunExpert magazine;  April 1991
  356.     Volume 2 Number 4.  The newest (Dec 92) Computer Language magazine
  357.     is also alleged to contain a cover article on Perl.
  358.  
  359.     The USENIX LISA (Large Installations Systems Administration) Conference
  360.     have for several years now included many papers of tools written in
  361.     Perl.  Old proceedings of these conferences are available; look in
  362.     your current issue of ";login:" or send mail to office@usenix.org 
  363.     for further information.
  364.  
  365.     C.  INTERNET
  366.  
  367.     For other examples of Perl scripts, look in the Perl source directory in
  368.     the eg subdirectory.  You can also find a good deal of them on 
  369.     archive.cis.ohio-state.edu in the pub/perl/scripts/ subdirectory.
  370.  
  371.     Another source for examples, currently only for anonymous FTP, is on
  372.     convex.com [130.168.1.1].  This contains, amongst other things,
  373.     a copy of the newsgroup up through Aug 91, a text retrieval database
  374.     for the newsgroup, a rather old and short troff version of Tom Christiansen's
  375.     perl tutorial (this was the version presented at Washington DC USENIX),
  376.     and quite a few of Tom's scripts.  You can look at the INDEX file
  377.     in /pub/perl/INDEX for a list of what's in that directory.   
  378.  
  379.     The Convex and Ohio State archives are mirrored on uunet
  380.     in /languages/perl/scripts-{convex,osu}.
  381.  
  382.     D.  REFERENCE GUIDE
  383.  
  384.     A nice reference guide by Johan Vromans <jv@mh.nl> is also available;
  385.     It is distributed in LaTeX (source) and PostScript (ready to
  386.     print) forms. Obsolete versions may still be available in TeX and troff
  387.     forms, although these don't print as nicely. The official kit
  388.     includes both LaTeX and PostScript forms, and can be FTP'd from
  389.     ftp.cs.ruu.nl [131.211.80.17], file /pub/DOC/perlref-4.035.tar.Z.
  390.     The reference guide comes with the O'Reilly book in a nice, glossy
  391.     card format.
  392.  
  393.     E.  PERL COURSES
  394.  
  395.     Various technical conferences, including USENIX, SUG, WCSAS, AUUG,
  396.     FedUnix, and Europen have been sponsoring tutorials of varying lengths
  397.     on Perl at their system administration and general conferences.  You
  398.     might consider attending one of these.  These classes are typically
  399.     taught by Tom Christiansen <tchrist@usenix.com>, although both Rob
  400.     Kolstad <kolstad@usenix.org> and Randal Schwartz <merlyn@ora.com> also
  401.     teach Perl on occasion.  Special appearances by Tom, Rob, and/or
  402.     Randal may also be negotiated.  Classes can run from one day up to a
  403.     week ranging over a wide range of subject matter (most are two or
  404.     three days), and can include lab time if you want; having lab time
  405.     with exercises is generally of great benefit.  Send us mail if your
  406.     organization is interested in having a Perl class taught at your site.
  407.  
  408.  
  409. 1.8) Can people who aren't on USENET receive comp.lang.perl as a digest?
  410.  
  411.     "Perl-Users" is the mailing list version of the comp.lang.perl
  412.     newsgroup.  If you're not lucky enough to be on USENET you can post to
  413.     comp.lang.perl by sending to one of the following addresses.  Which one
  414.     will work best for you depends on which nets your site is hooked into.
  415.     Ask your local network guru if you're not certain.
  416.  
  417.     Internet: PERL-USERS@VIRGINIA.EDU
  418.               Perl-Users@UVAARPA.VIRGINIA.EDU
  419.  
  420.     BitNet: Perl@Virginia
  421.  
  422.     uucp: ...!uunet!virginia!perl-users
  423.  
  424.     The Perl-Users list is bidirectionally gatewayed with the USENET
  425.     newsgroup comp.lang.perl.  This means that VIRGINIA functions as a
  426.     reflector.  All traffic coming in from the non-USENET side is
  427.     immediately posted to the newsgroup.  Postings from the USENET side are
  428.     periodically digested and mailed out to the Perl-Users mailing list.  A
  429.     digest is created and distributed at least once per day, more often if
  430.     traffic warrants.
  431.  
  432.     All requests to be added to or deleted from this list, problems,
  433.     questions, etc., should be sent to:
  434.  
  435.     Internet: Perl-Users-Request@Virginia.EDU
  436.               Perl-Users-Request@uvaarpa.Virginia.EDU
  437.  
  438.     BitNet: Perl-Req@Virginia
  439.  
  440.     uucp: ...!uunet!virginia!perl-users-request
  441.  
  442.     Coordinator: Marc Rouleau <mer6g@VIRGINIA.EDU>
  443.  
  444. 1.9) Are archives of comp.lang.perl available?
  445.  
  446.     Yes, although they're poorly organized.  You can get them from
  447.     the host ftp.cs.caltech.edu (131.215.128.204) in the directory  
  448.     /pub/comp.lang.perl.  The file is comp.lang.perl.tar.Z; this file
  449.     was last modified on February 15, 1992, and is 8.9 megabytes long.
  450.  
  451.     These are currently stored in news- or MH-style format; there are
  452.     subdirectories named things like "arrays", "programs", "taint", and
  453.     "emacs".  Unfortunately, only the first ~1600 or so messages have been
  454.     so categorized, and we're now up to almost 15000.  Furthermore, even
  455.     this categorization was haphazardly done and contains errors.  
  456.  
  457.     A more sophisticated query and retrieval mechanism is desirable.
  458.     Preferably one that allows you to retrieve article using a fast-access
  459.     indices, keyed on at least author, date, subject, thread (as in "trn")
  460.     and probably keywords.  Right now, the MH pick command works for this,
  461.     but it is very slow to select on 15000 articles.
  462.  
  463.     If you're serious about this, your best bet is probably to retrieve
  464.     the compressed tarchive and play with what you get.  Any suggestions
  465.     how to better sort this all out are extremely welcome.
  466.  
  467.     Currently the comp.lang.perl archives on convex.com are nearly a year
  468.     behind.  That's because I no longer have room to store them there.  I
  469.     do have them all on-line still, but they are not publicly accessible.
  470.     If you have a special request for a query on the old newsgroup
  471.     postings, and make nice noises in my direction, I can run the query
  472.     and send them to you.  Algebraic queries are like "find me anything
  473.     about this and that and the other thing but not this or whozits".  I
  474.     hope to put this in the form of a mailserver.  Donated software would
  475.     be fine. :-)
  476.  
  477.     The fast text-retrieval query system for this I'm currently using is
  478.     Liam Quin's excellent lqtext system, available from ftp.cs.toronto.edu
  479.     in /pub/lq-text* .
  480.  
  481.     Rumor has it that there are WAIS servers out there for comp.lang.perl
  482.     these days, but I haven't used them.  Any information on these would
  483.     be appreciated.
  484.  
  485.  
  486. 1.10) How do I get Perl to run on machine FOO?
  487.  
  488.     Perl comes with an elaborate auto-configuration script that allows Perl
  489.     to be painlessly ported to a wide variety of platforms, including many
  490.     non-UNIX ones.  Amiga and MS-DOS binaries are available on
  491.     jpl-devvax.jpl.nasa.gov [128.149.1.143] for anonymous FTP.  Try to bring
  492.     Perl up on your machine, and if you have problems, examine the README
  493.     file carefully, and if all else fails, post to comp.lang.perl;
  494.     probably someone out there has run into your problem and will be able
  495.     to help you.
  496.  
  497.     In particular, since they're so often asked about, here's some information 
  498.     for the MacIntosh from Matthias Ulrich Neeracher <neeri@iis.ethz.ch>:
  499.  
  500.     A port of Perl to the Apple Macintosh is available by anonymous
  501.     ftp to wuarchive.wustl.edu [128.252.135.4] from the file
  502.     /mirrors2/rascal.ics.utexas.edu/programming/Perl_402_MPW_CPT_bin .
  503.  
  504.     You can also get it from Host gatekeeper.dec.com [16.1.0.2]
  505.     in /.9/plan/perl/macperl/Perl_402_MPW_CPT_bin .
  506.  
  507.     The file is 1.1M and must be transferred in BINARY mode. Please
  508.     be considerate of the archive sites' users during CDT working hours.
  509.     (And, no, there is no way to get it by email).
  510.  
  511.     For European users, the file should soon appear on lth.se.
  512.  
  513.     To make optimal use of all the features of this port, you
  514.     should have MPW, ToolServer, and 5M of memory. There is also a
  515.     standalone version included, but it's currently of very limited
  516.     usefulness.
  517.  
  518.     This package contains all of the sources for compilation with
  519.     MPW C 3.2
  520.  
  521.     Here's more, from Timothy Murphy <tim@maths.tcd.ie >
  522.  
  523.  
  524.     I ported perl to the Mac, using Think C, a while ago.  I've
  525.     used it quite a lot since without problems.
  526.  
  527.     It is available from ftp.maths.tcd.ie in pub/Mac/perl.hqx .
  528.     The source (as diffs from the standard source) is in the
  529.     subdirectory pub/Mac/perl-4.035 .
  530.  
  531.     A Mac version of patch is also available in pub/Mac/patch.hqx
  532.     with source in pub/Mac/patch-2.0 .  Various other Mac ports of
  533.     GNU programs can be found in the same place.
  534.  
  535.     They all use a small "ThinkCPosix" library containing various
  536.     Unix-like functions, which again can be found in the same
  537.     place.
  538.  
  539.     And here's some VMS information from Rao V. Akella 
  540.     <rao@moose.cccs.umn.edu>:  (this appears to be an old port)
  541.  
  542.     You can pick up Perl for VMS (version 3.0.1.1 patchlevel 4) via
  543.     anonymous ftp from ftp.pitt.edu [130.49.253.1] in the
  544.     software/vms/perl subdirectory (there are two files there:
  545.     perl-pl18.bck and perl-pl4.bck).
  546.  
  547.     There is also a v3.018 on info.rz.uni-ulm.de [134.60.1.125] or
  548.     vms.huji.ac.il [128.139.4.3] in /pub/VMS/misc (information courtesy 
  549.     of Anders Rolff <rolff@scotty.eurokom.ie>).
  550.  
  551.     And here is a recent version for MS-DOS from Budi Rahard 
  552.     <rahard@ee.UManitoba.CA>, who says:
  553.  
  554.     I am collecting MS-DOS Perl(s) in ftp.ee.umanitoba.ca directory
  555.     /pub/msdos/perl.  Currently I received three versions of Perl v4.019
  556.     and one of 4.010.  (Tommy Thorn <tthorn@daimi.aau.dk> and Len Reed
  557.     <holos0!lbr@gatech.edu>)  
  558.  
  559.     There is now a 4.035 for 386 [DOS], Hitoshi Doi <doi@jrd.december.com>
  560.     port, is available ftp.ee.umanitoba.ca as /pub/msdos/perl/perl386.zoo .
  561.  
  562.     Please contact the porters directly in case of questions about
  563.     these ports.
  564.  
  565.  
  566. 1.11) Where can I get (info|inter|ora|sql|syb)perl?
  567.  
  568.     Numerous database-oriented extensions to Perl have been written.
  569.     These amount to using the usub mechanism (see the usub/ subdirectory
  570.     in the distribution tree) to link in a database library, allowing
  571.     embedded calls to Informix, Interbase, Oracle, Ingres, and Sybase.
  572.     There is currently a project underway, organized by Buzz Moschetti
  573.     <buzz@bear.com>, to create a higher level interface (DBperl) that
  574.     will allow you to write your queries in a database-independent
  575.     fashion.  If you're interested, send mail to
  576.     <perldb-interest-request@vix.com> about it.
  577.    
  578.     Meanwhile, here are the authors of the various extensions:
  579.  
  580.     What            Target DB       Who
  581.     --------        -----------     ----------------------------------------
  582.     Infoperl        Informix        Kurt Andersen (kurt@hpsdid.sdd.hp.com)
  583.     Interperl       Interbase       Buzz Moschetti (buzz@bear.com)
  584.     Oraperl         Oracle          Kevin Stock (kstock@encore.com)
  585.     Sqlperl         Ingres          Ted Lemon (mellon@ncd.com)
  586.     Sybperl         Sybase          Michael Peppler (mpeppler@itf.ch)
  587.  
  588.  
  589. 1.12) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  590.  
  591.     Because the Pascal people would be upset that we stole their name. :-)
  592.  
  593.     The dynamic nature of Perl's do and eval operators (and remember that
  594.     constructs like s/$mac_donald/$mac_gregor/eieio count as an eval) would
  595.     make this very difficult.  To fully support them, you would have to put
  596.     the whole Perl interpreter into each compiled version for those scripts
  597.     using them.  This is what undump does right now, if your machine has it.
  598.     If what you're doing will be faster in C than in Perl, maybe it should
  599.     have been written in C in the first place.  For things that ought to be
  600.     written in Perl, the interpreter will be just about as fast, because the
  601.     pattern matching routines won't work any faster linked into a C program.
  602.     Even in the case of simple Perl programs that don't do any fancy evals, the
  603.     major gain would be in compiling the control flow tests, with the rest
  604.     still being a maze of twisty, turny subroutine calls.  Since these are not
  605.     usually the major bottleneck in the program, there's not as much to be
  606.     gained via compilation as one might think.
  607.  
  608.  
  609. 1.13) Where can I get undump for my machine?
  610.  
  611.     The undump program comes from the TeX distribution.  If you have TeX, then
  612.     you may have a working undump.  If you don't, and you can't get one,
  613.     *AND* you have a GNU emacs working on your machine that can clone itself,
  614.     then you might try taking its unexec() function and compiling Perl with
  615.     -DUNEXEC, which will make Perl call unexec() instead of abort().  You'll
  616.     have to add unexec.o to the objects line in the Makefile.  If you succeed,
  617.     post to comp.lang.perl about your experience so others can benefit from it.
  618.  
  619.  
  620. 1.14) Where can I get a perl-mode for emacs?
  621.  
  622.     In the perl4.0 source directory, you'll find a directory called
  623.     "emacs", which contains several files that should help you.
  624.  
  625.  
  626. 1.15) How can I use Perl interactively?
  627.     
  628.     The easiest way to do this is to run Perl under its debugger.
  629.     If you have no program to debug, you can invoke the debugger
  630.     on an `empty' program like this:
  631.  
  632.         perl -de 0
  633.  
  634.     (The more positive amongst us prefer "perl -de 1". :-)
  635.  
  636.     Now you can type in any legal Perl code, and it will be immediately
  637.     evaluated.  You can also examine the symbol table, get stack
  638.     backtraces, check variable Values, and if you want to, set 
  639.     breakpoints and do the other things you can do in a symbolic debugger.
  640.  
  641.  
  642. 1.16) Is there a Perl shell? 
  643.     
  644.    Not really.  Perl is a programming language, not a command
  645.    interpreter.  There is a very simple one called "perlsh"
  646.    included in the Perl source distribution.  It just does this:
  647.  
  648.     $/ = '';        # set paragraph mode
  649.     $SHlinesep = "\n";
  650.     while ($SHcmd = <>) {
  651.         $/ = $SHlinesep;
  652.         eval $SHcmd; print $@ || "\n";
  653.         $SHlinesep = $/; $/ = '';
  654.     }
  655.  
  656.    Not very interesting, eh?  
  657.  
  658.    Daniel Smith <dansmith@autodesk.com> is working on an interactive Perl
  659.    shell called SoftList.  It's currently at version 3.0beta.  SoftList
  660.    3.0 has tcsh-like command line editing, can let you define a file of
  661.    aliases so that you can run chunks of perl or UNIX commands, and so
  662.    on.  You can send mail to him for further information and availability.
  663.  
  664.  
  665. 1.17) Is there a Perl profiler?
  666.  
  667.     While there isn't one included with the perl source distribution,
  668.     various folks have written packages that allow you to do at least some
  669.     sort of profiling.  The strategy usually includes modifying the perl
  670.     debugger to handle profiling.  Authors of these packages include
  671.  
  672.     Wayne Thompson         <me@anywhere.EBay.Sun.COM>
  673.     Ray Lischner         <lisch@sysserver1.mentor.com>
  674.     Kresten Krab Thorup     <krab@iesd.auc.dk>  
  675.  
  676.     The original articles by these folks containing their
  677.     profilers are available on convex.com in 
  678.     /pub/perl/information/profiling.shar via anon ftp.
  679.  
  680.  
  681. 1.18) Is there a yacc for Perl?
  682.  
  683.     Yes!! It's a version of Berkeley yacc that outputs Perl code instead
  684.     of C code!  You can get this from ftp.sterling.com [192.124.9.1] in
  685.     /local/perl-byacc1.8.1.tar.Z, or send the author mail for details.
  686.  
  687.  
  688. 1.19) How can I use curses with perl?
  689.  
  690.     One way is to build a curseperl binary by linking in your C curses
  691.     library as described in the usub subdirectory of the perl sources.
  692.     This requires a modicum of work, but it will be reasonably fast
  693.     since it's all in C (assuming you consider curses reasonably fast. :-)  
  694.     Programs written using this method require the modified curseperl,
  695.     not vanilla perl, to run.  While this is something of a disadvantage,
  696.     experience indicates that it's better to use curseperl than to 
  697.     try to roll your own using termcap directly.
  698.  
  699.     Another possibility is to use Henk Penning's cterm package, a curses
  700.     emulation library written in perl.  cterm is actually a separate
  701.     program with which you communicate via a pipe.  It is available from
  702.     ftp.cs.ruu.nl [131.211.80.17] via anonymous ftp. in the directory
  703.     pub/PERL.  You may also acquire the package via email in compressed,
  704.     uuencoded form by sending a message to mail-server@cs.ruu.nl
  705.     containing these lines:
  706.  
  707.     begin
  708.     send PERL/cterm.shar.Z
  709.     end
  710.  
  711.     See the question on retrieving perl via mail for more information on
  712.     how to get retrieve other items of interest from the mail server
  713.     there.
  714.  
  715.  
  716. 1.20) How can I use X with Perl?
  717.  
  718.     Right now, you have several choices.  You can wait for perl5, use
  719.     the WAFE or STDWIN packages, or try to make your own usub bindings. 
  720.  
  721.     Perl5 is anticipated to be released with bindings for X, called 
  722.     guiperl.  An exciting prototype for this, written by Jon Biggar
  723.     <jon@netlabs.com>, Larry's *other* brother-in-law and officemate, 
  724.     is already up and running inside of Netlabs.  This program addresses
  725.     the same dynamic gui-building problem space as does tcl/tk.
  726.     
  727.     If you can't wait or don't think that guiperl will do what you want,
  728.     a stab at Motif bindings was begun by Theodore C. Law
  729.     <TEDLAW@TOROLAB6.VNET.IBM.COM> area.  His article about this is 
  730.     on convex.com in /pub/perl/info/motif for anon ftp.
  731.  
  732.     STDWIN is a library written by Guido van Rossum <guido@cwi.nl>
  733.     (author of the Python programming language) that is portable 
  734.     between Mac, Dos and X11.  One could write a Perl agent to
  735.     speak to this STDWIN server.
  736.  
  737.     WAFE is a package that implements a symbolic interface to the Athena
  738.     widgets (X11R5). A typical Wafe application consists in our framework
  739.     of two parts: the front-end (we call it Wafe for Widget[Athena]front
  740.     end) and an application program running typically as separate process.
  741.     The application program can be implemented in an arbitrary programming
  742.     language and talks to the front-end via stdio.  Since Wafe (the
  743.     front-end) was developed using the extensible TCL shell (cite John
  744.     Ousterhout), an application program can dynamically submit requests to
  745.     the front-end to build up the graphical user interface; the
  746.     application can even down-load application specific procedures into
  747.     the front-end.  The distribution contains sample application programs
  748.     in Perl, GAWK, Prolog, TCL, and C talking to the same Wafe binary.
  749.     Many of the demo applications are implemented in Perl.  Wafe 0.9 can
  750.     be obtained via anonymous ftp from 
  751.     ftp.wu-wien.ac.at:pub/src/X11/wafe-0.9.tar.Z
  752.     (for people without name server: the ip address is 137.208.3.5)
  753.  
  754.  
  755. 1.21) What is perl4?  What is perl5?
  756.  
  757.     The answer to what is perl4 is nearly anything you might otherwise 
  758.     program in shell or C.  The answer to what is perl5 is basically
  759.     Perl: the Next Generation.  In fact, it's essentially a complete
  760.     rewrite of perl from the bottom up, and back again.
  761.  
  762.     Larry gave a talk on perl5 at a Bay LISA meeting as well as at the
  763.     most recent USENIX LISA conference in Long Beach in which he timorously
  764.     admitted that perl5 might possibly be beta released in early 1993.
  765.     He enumerated some of the following features.  Note that not only have
  766.     not all these been implemented yet, the ones further down the list
  767.     might well not get done at all.
  768.  
  769.     a faster, tighter, more flexible interpreter
  770.     very easy GUI Perl applications using X bindings ("guiperl")
  771.     embeddable Perl code in C code: cc prog.c -lperl 
  772.     multiple coresident perl interpreters:
  773.         perhaps threading and/or coroutines
  774.     named argument passing:
  775.         some_func( OC => $red, TOF => "\f");
  776.     recursive lists:
  777.         [a, b, [c, d], e] has 4 elts, the 3rd being itself a list
  778.     typed pointers and generalized indirection:
  779.         like @{$aptr} or &{$fptr} or &{ $table[$index] . "func" }().
  780.     merging of list operator and function calling syntax:
  781.         split /pat/, $string;
  782.     subroutines without &'s:   myfunc($arg);
  783.     generalization of dbm binding for assoc arrays to handle
  784.         any generic fetch/store/open/close/flush package.
  785.         (thus allowing both dbm and gdbm at once)
  786.     object oriented programming:
  787.         STDOUT->flush(1);
  788.         give dog $bone;
  789.     lexical scoping
  790.     dynamic loading of C libraries for systems that can
  791.     byte-compiled code for speed and maybe security
  792.  
  793.     It's tempting to want this stuff soon, since the sooner it comes
  794.     out the sooner we can all build really cool applications.  But the
  795.     longer Larry works on it, the more items from this list will actually
  796.     get done, and the more robust the release will be.  So let's not
  797.     ask him about it too often.
  798.  
  799.  
  800. 1.22) How does Perl compare with languages like REXX or TCL?
  801.  
  802.     REXX is an interpreted programming language first seen on IBM systems,
  803.     and TCL is John Ousterhout's embeddable command language.  TCL's most
  804.     intriguing feature for many people is the tcl/tk toolset that allows
  805.     for interpreted X-based tools.
  806.  
  807.     To avoid any flamage, if you really want to know the answer to this
  808.     question, probably the best thing to do is try to write equivalent
  809.     code to do a set of tasks.  All three have their own newsgroups in
  810.     which you can learn about (but hopefully not argue about) these
  811.     languages.
  812.  
  813.     To find out more about these or other languages, you might also check
  814.     out David Muir Sharnoff <muir@tfs.com>'s posting on "Catalog of
  815.     compilers, interpreters, and other language tools" which he posts to
  816.     comp.lang.misc, comp.sources.d, comp.archives.admin, and the
  817.     news.answers newsgroups.  It's a comprehensive treatment of many
  818.     different languages.  (Caveat lector: he considers Perl's syntax
  819.     "unappealing".)   This list is archived on convex.com in 
  820.     /pub/perl/info/lang-survey.shar .
  821.  
  822.  
  823. 1.23) Is it a Perl program or a Perl script?
  824.  
  825.     Certainly. :-)
  826.  
  827.     Current UNIX parlance holds that anything interpreted
  828.     is a script, and anything compiled into native machine
  829.     code is a program.  However, others hold that a program
  830.     is a program is a program: after all, one seldom discusses
  831.     scripts written in BASIC or LISP.  Larry considers it
  832.     a program if it's set in stone and you can't change it,
  833.     whereas if you go in and hack on it, then it's a script.
  834.  
  835.     But doesn't really matter.  The terms are generally 
  836.     interchangeable today.
  837.  
  838.  
  839. 1.24) What's the difference between "Perl" and "perl"?
  840.  
  841.      32 :-)  [  ord('p') - ord('P')  ]
  842.  
  843.      Larry now uses "Perl" to signify the language proper and "perl" the
  844.      implementation of it, i.e. the current interpreter.  Hence my quip
  845.      that "Nothing but perl can parse Perl."
  846.  
  847.      On the other hand, the aesthetic value of casewise parallelism
  848.      in "awk", "sed", and "perl" as much require the lower-case 
  849.      version as "C", "Pascal", and "Perl" require the 
  850.      upper-case version.  It's also easier to type "Perl" in 
  851.      typeset print than to be constantly switching in Courier. :-)
  852.     
  853.      In other words, it doesn't matter much, especially if all
  854.      you're doing is hearing someone talk about the language;
  855.      case is hard to distingish aurally.
  856.  
  857.  
  858. 1.25) What companies use or ship Perl?
  859.  
  860.     At this time, the known list of companies that ship Perl includes at
  861.     least the following: 
  862.  
  863.     BSDI
  864.     Comdisco Systems
  865.     CONVEX Computer Corporation
  866.     Dell
  867.     Integraph
  868.     Kubota Pacific (/usr/contrib)
  869.     Netlabs
  870.  
  871.     Many other companies use Perl internally for purposes of tools
  872.     development, systems administration, installation scripts, and test
  873.     suites.  Rumor has it that the large workstation vendors (the TLA set)
  874.     are seriously looking into shipping Perl with their standard systems
  875.     "soon".
  876.  
  877.     People with support contracts with their vendors are actively 
  878.     encouraged to submit enhancement requests that Perl be shipped 
  879.     as part of their standard system.  It would, at the very least,
  880.     reduce the FTP load on the Internet. :-)
  881.  
  882.  
  883. 1.26) Is there commercial, 3rd-party support for Perl?
  884.  
  885.     No.  Although perl is included in the GNU distribution, at last check,
  886.     Cygnus does not offer support for it.  However, it's unclear whether
  887.     they've ever been offered sufficient financial incentive to do so.
  888.  
  889.     On the other hand, you do have comp.lang.perl as a totally gratis
  890.     support mechanism.  As long as you ask "interesting" questions, 
  891.     you'll probably get plenty of help. :-)
  892.  
  893. 1.27) Where can I get a list of the JAPH signature quotes?
  894.  
  895.     These are the "just another perl hacker" signatures that
  896.     some people sign their postings with.  About 100 of the 
  897.     of the earlier ones are on convex.com in /pub/perl/info/japh.
  898.  
  899. 1.28) Where can I get a list of Larry Wall witticisms?
  900.  
  901.     Over a hundred quips by Larry, from postings of his or source code,
  902.     can be found on convex.com in /pub/perl/info/lwall-quotes.  
  903.  
  904. 1.29) Is there a pretty-printer for Perl?
  905.  
  906.     That depends on what you mean.  If you want something 
  907.     that works like vgrind on Perl programs, then the answer
  908.     is "yes, nearly".  Here's a vgrind entry for perl:
  909.  
  910.     PERL|perl|Perl:\
  911.         :pb=(^\d?sub\d\p\d?|\{):\
  912.         :bb={:be=}:cb=#:ce=$:sb=":se=\e":lb=':\
  913.         :le=\e':tl:\
  914.         :id=_:\
  915.         :kw=\
  916.         if for foreach unless until while continue else elsif \
  917.         do eval require \
  918.         die exit \
  919.         defined delete reset \
  920.         goto last redo next dump \
  921.         local undef return  \
  922.         write format  \
  923.         sub package
  924.  
  925.     It doesn't actually do everything right; in particular, 
  926.     things like $#, $', s#/foo##, and $foo'bar all confuse it.
  927.  
  928.     If what you mean is whether there is a program that will
  929.     reformat the program much as indent(1) will do for C, then
  930.     the answer is no.  The complex feedback between the scanner
  931.     and the parser (as in the things that confuse vgrind) make
  932.     it challenging to write at best to write a stand-alone C parser.
  933.  
  934. print "Just another Perl hacker,"
  935. -- 
  936. Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
  937. merlyn@ora.com (semi-permanent) merlyn@kandinsky.intel.com (NEWSREADING ONLY)
  938. Quote: "Welcome to Portland, Oregon, home of the California Raisins!"
  939. Xref: ruuinf comp.lang.perl:16472 news.answers:9356 comp.answers:1106
  940. Path: ruuinf!sun4nl!mcsun!uunet!news.cnri.reston.va.us!newsserver.jvnc.net!howland.reston.ans.net!gatech!asuvax!chnews!ornews.intel.com!news
  941. From: Randal L. Schwartz <merlyn@ora.com>
  942. Newsgroups: comp.lang.perl,news.answers,comp.answers
  943. Subject: comp.lang.perl FAQ (part 2 of 2)
  944. Followup-To: comp.lang.perl
  945. Date: 23 Jun 93 17:49:58 GMT
  946. Organization: Intel Corporation
  947. Lines: 1354
  948. Approved: news-answers-request@MIT.Edu
  949. Message-ID: <merlyn.740857798.6721.3@kandinsky.intel.com>
  950. NNTP-Posting-Host: kandinsky.intel.com
  951.  
  952. Archive-name: perl-faq/part2
  953. Version: $Id: perl-tech,v 1.2 92/11/30 05:22:44 tchrist Exp Locker: tchrist $
  954.  
  955. [I have not changed anything here, but I haven't seen Tom post this in
  956. a while.  Maybe I'm going to become the FAQ maintainer... sigh.  For
  957. one thing, this FAQ doesn't address the Llama Book... a glaring
  958. oversight. :-)
  959.  
  960. This version is slightly updated from the one I posted a few days
  961. ago, as pointed out to me by Henk Penning <henkp@cs.ruu.nl>.
  962.  
  963. -- merlyn@ora.com]
  964.  
  965. This posting contains answers to the following techical questions
  966. regarding Perl:
  967.  
  968. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  969. 2.2) Why don't backticks work as they do in shells?  
  970. 2.3) How come Perl operators have different precedence than C operators?
  971. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  972. 2.5) How can I call my system's unique C functions from Perl?
  973. 2.6) Where do I get the include files to do ioctl() or syscall()?
  974. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  975. 2.8) How can I detect keyboard input without reading it?
  976. 2.9) How can I make an array of arrays or other recursive data types?
  977. 2.10) How can I quote a variable to use in a regexp?
  978. 2.11) Why do setuid Perl scripts complain about kernel problems?
  979. 2.12) How do I open a pipe both to and from a command?
  980. 2.13) How can I change the first N letters of a string?
  981. 2.14) How can I manipulate fixed-record-length files?
  982. 2.15) How can I make a file handle local to a subroutine?
  983. 2.16) How can I extract just the unique elements of an array?
  984. 2.17) How can I call alarm() or usleep() from Perl?
  985. 2.18) How can I test whether an array contains a certain element?
  986. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  987. 2.20) Why doesn't Perl interpret my octal data octally?
  988. 2.21) How do I sort an associative array by value instead of by key?
  989. 2.22) How can I capture STDERR from an external command?
  990. 2.23) Why doesn't open return an error when a pipe open fails?
  991. 2.24) How can I compare two date strings?
  992. 2.25) What's the fastest way to code up a given task in perl?
  993. 2.26) How can I know how many entries are in an associative array?
  994. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  995. 2.28) Do I always/never have to quote my strings or use semicolons?
  996. 2.29) How can I translate tildes in a filename?
  997. 2.30) How can I convert my shell script to Perl?
  998. 2.31) What is variable suicide and how can I prevent it?
  999. 2.32) Can I use Perl regular expressions to match balanced text?
  1000. 2.33) Can I use Perl to run a telnet or ftp session?
  1001. 2.34) What does "Malformed command links" mean?
  1002. 2.35) How can I set up a footer format to be used with write()?
  1003. 2.36) Why does my Perl program keep growing in size?
  1004.  
  1005.  
  1006. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  1007.  
  1008.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  1009.     and % for hashed arrays.  The * means all types of that symbol name
  1010.     and are sometimes used like pointers; the <> are used for inputting
  1011.     a record from a filehandle.  See the question on arrays of arrays
  1012.     for more about Perl pointers.
  1013.  
  1014.     Always make sure to use a $ for single values and @ for multiple ones.
  1015.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  1016.     which is a list of length one (not a scalar), and is a fairly common
  1017.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  1018.     not really doing what you think it's doing for the reason you think
  1019.     it's doing it, which means one of these days, you'll shoot yourself
  1020.     in the foot; ponder for a moment what these will really do:
  1021.     @foo[0] = `cmd args`;
  1022.     @foo[2] = <FILE>;
  1023.     Just always say $foo[2] and you'll be happier.
  1024.  
  1025.     This may seem confusing, but try to think of it this way:  you use the
  1026.     character of the type which you *want back*.  You could use @foo[1..3] for
  1027.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  1028.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  1029.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  1030.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  1031.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  1032.  
  1033.     While there are a few places where you don't actually need these type
  1034.     specifiers, except for files, you should always use them.  Note that
  1035.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  1036.     getline function, that is, it reads a line from the handle FILE.  When
  1037.     doing open, close, and other operations besides the getline function on
  1038.     files, do NOT use the brackets.
  1039.  
  1040.     Beware of saying:
  1041.     $foo = BAR;
  1042.     Which wil be interpreted as 
  1043.     $foo = 'BAR';
  1044.     and not as 
  1045.     $foo = <BAR>;
  1046.     If you always quote your strings, you'll avoid this trap.
  1047.  
  1048.     Normally, files are manipulated something like this (with appropriate
  1049.     error checking added if it were production code):
  1050.  
  1051.     open (FILE, ">/tmp/foo.$$");
  1052.     print FILE "string\n";
  1053.     close FILE;
  1054.  
  1055.     If instead of a filehandle, you use a normal scalar variable with file
  1056.     manipulation functions, this is considered an indirect reference to a
  1057.     filehandle.  For example,
  1058.  
  1059.     $foo = "TEST01";
  1060.     open($foo, "file");
  1061.  
  1062.     After the open, these two while loops are equivalent:
  1063.  
  1064.     while (<$foo>) {}
  1065.     while (<TEST01>) {}
  1066.  
  1067.     as are these two statements:
  1068.     
  1069.     close $foo;
  1070.     close TEST01;
  1071.  
  1072.     but NOT to this:
  1073.  
  1074.     while (<$TEST01>) {} # error
  1075.         ^
  1076.         ^ note spurious dollar sign
  1077.  
  1078.     This is another common novice mistake; often it's assumed that
  1079.  
  1080.     open($foo, "output.$$");
  1081.  
  1082.     will fill in the value of $foo, which was previously undefined.  
  1083.     This just isn't so -- you must set $foo to be the name of a valid
  1084.     filehandle before you attempt to open it.
  1085.  
  1086.  
  1087. 2.2) Why don't backticks work as they do in shells?  
  1088.  
  1089.     Several reason.  One is because backticks do not interpolate within
  1090.     double quotes in Perl as they do in shells.  
  1091.     
  1092.     Let's look at two common mistakes:
  1093.  
  1094.          $foo = "$bar is `wc $file`";  # WRONG
  1095.  
  1096.     This should have been:
  1097.  
  1098.      $foo = "$bar is " . `wc $file`;
  1099.  
  1100.     But you'll have an extra newline you might not expect.  This
  1101.     does not work as expected:
  1102.  
  1103.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  1104.  
  1105.     Because backticks do not automatically eat trailing or embedded
  1106.     newlines.  The chop() function will remove the last character from
  1107.     a string.  This should have been:
  1108.  
  1109.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  1110.  
  1111.     You should also be aware that while in the shells, embedding
  1112.     single quotes will protect variables, in Perl, you'll need 
  1113.     to escape the dollar signs.
  1114.  
  1115.     Shell: foo=`cmd 'safe $dollar'`
  1116.     Perl:  $foo=`cmd 'safe \$dollar'`;
  1117.     
  1118.  
  1119. 2.3) How come Perl operators have different precedence than C operators?
  1120.  
  1121.     Actually, they don't; all C operators have the same precedence in Perl as
  1122.     they do in C.  The problem is with a class of functions called list
  1123.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  1124.     bizarre in that they have different precedence depending on whether you
  1125.     look on the left or right of them.  Basically, they gobble up all things
  1126.     on their right.  For example,
  1127.  
  1128.     unlink $foo, "bar", @names, "others";
  1129.  
  1130.     will unlink all those file names.  A common mistake is to write:
  1131.  
  1132.     unlink "a_file" || die "snafu";
  1133.  
  1134.     The problem is that this gets interpreted as
  1135.  
  1136.     unlink("a_file" || die "snafu");
  1137.  
  1138.     To avoid this problem, you can always make them look like function calls
  1139.     or use an extra level of parentheses:
  1140.  
  1141.     (unlink "a_file") || die "snafu";
  1142.     unlink("a_file")  || die "snafu";
  1143.  
  1144.     Sometimes you actually do care about the return value:
  1145.  
  1146.     unless ($io_ok = print("some", "list")) { } 
  1147.  
  1148.     Yes, print() return I/O success.  That means
  1149.  
  1150.     $io_ok = print(2+4) * 5;
  1151.  
  1152.     returns 5 times whether printing (2+4) succeeded, and 
  1153.     print(2+4) * 5;
  1154.     returns the same 5*io_success value and tosses it.
  1155.  
  1156.     See the Perl man page's section on Precedence for more gory details,
  1157.     and be sure to use the -w flag to catch things like this.
  1158.  
  1159.  
  1160. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  1161.  
  1162.     The natural way to program in those languages may not make for the fastest
  1163.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  1164.     see the a2p man page for tweaks you can make.
  1165.  
  1166.     Two of Perl's strongest points are its associative arrays and its regular
  1167.     expressions.  They can dramatically speed up your code when applied
  1168.     properly.  Recasting your code to use them can help a lot.
  1169.  
  1170.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  1171.     * operators can take a very long time to compute.  Don't use ()'s unless
  1172.     you really need them.  Anchor your string to the front if you can.
  1173.  
  1174.     Something like this:
  1175.     next unless /^.*%.*$/; 
  1176.     runs more slowly than the equivalent:
  1177.     next unless /%/;
  1178.  
  1179.     Note that this:
  1180.     next if /Mon/;
  1181.     next if /Tue/;
  1182.     next if /Wed/;
  1183.     next if /Thu/;
  1184.     next if /Fri/;
  1185.     runs faster than this:
  1186.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  1187.     which in turn runs faster than this:
  1188.     next if /Mon|Tue|Wed|Thu|Fri/;
  1189.     which runs *much* faster than:
  1190.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  1191.  
  1192.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  1193.  
  1194.     Remember that a printf costs more than a simple print.
  1195.  
  1196.     Don't split() every line if you don't have to.
  1197.  
  1198.     Another thing to look at is your loops.  Are you iterating through 
  1199.     indexed arrays rather than just putting everything into a hashed 
  1200.     array?  For example,
  1201.  
  1202.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  1203.  
  1204.     for $i ($[ .. $#list) {
  1205.         if ($pattern eq $list[$i]) { $found++; } 
  1206.     } 
  1207.  
  1208.     First of all, it would be faster to use Perl's foreach mechanism
  1209.     instead of using subscripts:
  1210.  
  1211.     foreach $elt (@list) {
  1212.         if ($pattern eq $elt) { $found++; } 
  1213.     } 
  1214.  
  1215.     Better yet, this could be sped up dramatically by placing the whole
  1216.     thing in an associative array like this:
  1217.  
  1218.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  1219.          'mno', 1, 'pqr', 1, 'stv', 1 );
  1220.     $found += $list{$pattern};
  1221.     
  1222.     (but put the %list assignment outside of your input loop.)
  1223.  
  1224.     You should also look at variables in regular expressions, which is
  1225.     expensive.  If the variable to be interpolated doesn't change over the
  1226.     life of the process, use the /o modifier to tell Perl to compile the
  1227.     regexp only once, like this:
  1228.  
  1229.     for $i (1..100) {
  1230.         if (/$foo/o) {
  1231.         &some_func($i);
  1232.         } 
  1233.     } 
  1234.  
  1235.     Finally, if you have a bunch of patterns in a list that you'd like to 
  1236.     compare against, instead of doing this:
  1237.  
  1238.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1239.     foreach $pat (@pats) {
  1240.         if ( $name =~ /^$pat$/ ) {
  1241.         &some_func();
  1242.         last;
  1243.         }
  1244.     }
  1245.  
  1246.     If you build your code and then eval it, it will be much faster.
  1247.     For example:
  1248.  
  1249.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1250.     $code = <<EOS
  1251.         while (<>) { 
  1252.             study;
  1253. EOS
  1254.     foreach $pat (@pats) {
  1255.         $code .= <<EOS
  1256.         if ( /^$pat\$/ ) {
  1257.             &some_func();
  1258.             next;
  1259.         }
  1260. EOS
  1261.     }
  1262.     $code .= "}\n";
  1263.     print $code if $debugging;
  1264.     eval $code;
  1265.  
  1266.  
  1267.  
  1268. 2.5) How can I call my system's unique C functions from Perl?
  1269.  
  1270.     If these are system calls and you have the syscall() function, then
  1271.     you're probably in luck -- see the next question.  For arbitrary
  1272.     library functions, it's not quite so straight-forward.  While you
  1273.     can't have a C main and link in Perl routines, if you're
  1274.     determined, you can extend Perl by linking in your own C routines.
  1275.     See the usub/ subdirectory in the Perl distribution kit for an example
  1276.     of doing this to build a Perl that understands curses functions.  It's
  1277.     neither particularly easy nor overly-documented, but it is feasible.
  1278.  
  1279.  
  1280. 2.6) Where do I get the include files to do ioctl() or syscall()?
  1281.  
  1282.     These are generated from your system's C include files using the h2ph
  1283.     script (once called makelib) from the Perl source directory.  This will
  1284.     make files containing subroutine definitions, like &SYS_getitimer, which
  1285.     you can use as arguments to your function.
  1286.  
  1287.     You might also look at the h2pl subdirectory in the Perl source for how to
  1288.     convert these to forms like $SYS_getitimer; there are both advantages and
  1289.     disadvantages to this.  Read the notes in that directory for details.  
  1290.    
  1291.     In both cases, you may well have to fiddle with it to make these work; it
  1292.     depends how funny-looking your system's C include files happen to be.
  1293.  
  1294.     If you're trying to get at C structures, then you should take a look
  1295.     at using c2ph, which uses debugger "stab" entries generated by your
  1296.     BSD or GNU C compiler to produce machine-independent perl definitions
  1297.     for the data structures.  This allows to you avoid hardcoding
  1298.     structure layouts, types, padding, or sizes, greatly enhancing
  1299.     portability.  c2ph comes with the perl distribution.  On an SCO
  1300.     system, GCC only has COFF debugging support by default, so you'll have
  1301.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  1302.     get c2ph to work there.
  1303.  
  1304.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  1305.     for more traps and tips on this process.
  1306.  
  1307.  
  1308. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  1309.  
  1310.     Well, it does.  The thing to remember is that local() provides an array
  1311.     context, and that the <FILE> syntax in an array context will read all the
  1312.     lines in a file.  To work around this, use:
  1313.  
  1314.     local($foo);
  1315.     $foo = <FILE>;
  1316.  
  1317.     You can use the scalar() operator to cast the expression into a scalar
  1318.     context:
  1319.  
  1320.     local($foo) = scalar(<FILE>);
  1321.  
  1322.  
  1323. 2.8) How can I detect keyboard input without reading it?
  1324.  
  1325.     You should check out the Frequently Asked Questions list in
  1326.     comp.unix.* for things like this: the answer is essentially the same.
  1327.     It's very system dependent.  Here's one solution that works on BSD
  1328.     systems:
  1329.  
  1330.     sub key_ready {
  1331.         local($rin, $nfd);
  1332.         vec($rin, fileno(STDIN), 1) = 1;
  1333.         return $nfd = select($rin,undef,undef,0);
  1334.     }
  1335.  
  1336.     A closely related question is how to input a single character from the
  1337.     keyboard.  Again, this is a system dependent operation.  The following 
  1338.     code that may or may not help you:
  1339.  
  1340.     $BSD = -f '/vmunix';
  1341.     if ($BSD) {
  1342.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  1343.     }
  1344.     else {
  1345.         system "stty", '-icanon',
  1346.         system "stty", 'eol', "\001"; 
  1347.     }
  1348.  
  1349.     $key = getc(STDIN);
  1350.  
  1351.     if ($BSD) {
  1352.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  1353.     }
  1354.     else {
  1355.         system "stty", 'icanon';
  1356.         system "stty", 'eol', '^@'; # ascii null
  1357.     }
  1358.     print "\n";
  1359.  
  1360.     You could also handle the stty operations yourself for speed if you're
  1361.     going to be doing a lot of them.  This code works to toggle cbreak
  1362.     and echo modes on a BSD system:
  1363.  
  1364.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  1365.     local($on) = $_[0];
  1366.     local($sgttyb,@ary);
  1367.     require 'sys/ioctl.ph';
  1368.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  1369.  
  1370.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  1371.  
  1372.     @ary = unpack($sgttyb_t,$sgttyb);
  1373.     if ($on) {
  1374.         $ary[4] |= &CBREAK;
  1375.         $ary[4] &= ~&ECHO;
  1376.     } else {
  1377.         $ary[4] &= ~&CBREAK;
  1378.         $ary[4] |= &ECHO;
  1379.     }
  1380.     $sgttyb = pack($sgttyb_t,@ary);
  1381.  
  1382.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  1383.     }
  1384.  
  1385.     Note that this is one of the few times you actually want to use the
  1386.     getc() function; it's in general way too expensive to call for normal
  1387.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  1388.     or sysread() functions.
  1389.  
  1390.     For perspectives on more portable solutions, use anon ftp to retrieve
  1391.     the file /pub/perl/info/keypress from convex.com.
  1392.  
  1393.  
  1394. 2.9) How can I make an array of arrays or other recursive data types?
  1395.  
  1396.     Remember that Perl isn't about nested data structures (actually,
  1397.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  1398.     somewhat).  It's about flat ones, so if you're trying to do this, you
  1399.     may be going about it the wrong way or using the wrong tools.  You
  1400.     might try parallel arrays with common subscripts.
  1401.  
  1402.     But if you're bound and determined, you can use the multi-dimensional
  1403.     array emulation of $a{'x','y','z'}, or you can make an array of names
  1404.     of arrays and eval it.
  1405.  
  1406.     For example, if @name contains a list of names of arrays, you can 
  1407.     get at a the j-th element of the i-th array like so:
  1408.  
  1409.     $ary = $name[$i];
  1410.     $val = eval "\$$ary[$j]";
  1411.  
  1412.     or in one line
  1413.  
  1414.     $val = eval "\$$name[$i][\$j]";
  1415.  
  1416.     You could also use the type-globbing syntax to make an array of *name
  1417.     values, which will be more efficient than eval.  Here @name hold
  1418.     a list of pointers, which we'll have to dereference through a temporary
  1419.     variable.
  1420.  
  1421.     For example:
  1422.  
  1423.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  1424.  
  1425.     In fact, you can use this method to make arbitrarily nested data
  1426.     structures.  You really have to want to do this kind of thing
  1427.     badly to go this far, however, as it is notationally cumbersome.
  1428.  
  1429.     Let's assume you just simply *have* to have an array of arrays of
  1430.     arrays.  What you do is make an array of pointers to arrays of
  1431.     pointers, where pointers are *name values described above.  You
  1432.     initialize the outermost array normally, and then you build up your
  1433.     pointers from there.  For example:
  1434.  
  1435.     @w = ( 'ww' .. 'xx' );
  1436.     @x = ( 'xx' .. 'yy' );
  1437.     @y = ( 'yy' .. 'zz' );
  1438.     @z = ( 'zz' .. 'zzz' );
  1439.  
  1440.     @ww = reverse @w;
  1441.     @xx = reverse @x;
  1442.     @yy = reverse @y;
  1443.     @zz = reverse @z;
  1444.  
  1445.     Now make a couple of array of pointers to these:
  1446.  
  1447.     @A = ( *w, *x, *y, *z );
  1448.     @B = ( *ww, *xx, *yy, *zz );
  1449.  
  1450.     And finally make an array of pointers to these arrays:
  1451.  
  1452.     @AAA = ( *A, *B );
  1453.  
  1454.     To access an element, such as AAA[i][j][k], you must do this:
  1455.  
  1456.     local(*foo) = $AAA[$i];
  1457.     local(*bar) = $foo[$j];
  1458.     $answer = $bar[$k];
  1459.  
  1460.     Similar manipulations on associative arrays are also feasible.
  1461.  
  1462.     You could take a look at recurse.pl package posted by Felix Lee
  1463.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  1464.     associative arrays) by using type glob references and some pretty serious
  1465.     wizardry.
  1466.  
  1467.     In C, you're used to creating recursive datatypes for operations
  1468.     like recursive decent parsing or tree traversal.  In Perl, these
  1469.     algorithms are best implemented using associative arrays.  Take an
  1470.     array called %parent, and build up pointers such that $parent{$person}
  1471.     is the name of that person's parent.  Make sure you remember that
  1472.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  1473.     be used to implement general graph traversal algorithms as well.
  1474.  
  1475.  
  1476. 2.10) How can I quote a variable to use in a regexp?
  1477.  
  1478.     From the manual:
  1479.  
  1480.     $pattern =~ s/(\W)/\\$1/g;
  1481.  
  1482.     Now you can freely use /$pattern/ without fear of any unexpected
  1483.     meta-characters in it throwing off the search.  If you don't know
  1484.     whether a pattern is valid or not, enclose it in an eval to avoid
  1485.     a fatal run-time error.
  1486.  
  1487.  
  1488. 2.11) Why do setuid Perl scripts complain about kernel problems?
  1489.  
  1490.     This message:
  1491.  
  1492.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  1493.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  1494.  
  1495.     is triggered because setuid scripts are inherently insecure due to a
  1496.     kernel bug.  If your system has fixed this bug, you can compile Perl
  1497.     so that it knows this.  Otherwise, create a setuid C program that just
  1498.     execs Perl with the full name of the script.  
  1499.  
  1500.  
  1501. 2.12) How do I open a pipe both to and from a command?
  1502.  
  1503.     In general, this is a dangerous move because you can find yourself in a
  1504.     deadlock situation.  It's better to put one end of the pipe to a file.
  1505.     For example:
  1506.  
  1507.     # first write some_cmd's input into a_file, then 
  1508.     open(CMD, "some_cmd its_args < a_file |");
  1509.     while (<CMD>) {
  1510.  
  1511.     # or else the other way; run the cmd
  1512.     open(CMD, "| some_cmd its_args > a_file");
  1513.     while ($condition) {
  1514.         print CMD "some output\n";
  1515.         # other code deleted
  1516.     } 
  1517.     close CMD || warn "cmd exited $?";
  1518.  
  1519.     # now read the file
  1520.     open(FILE,"a_file");
  1521.     while (<FILE>) {
  1522.  
  1523.     If you have ptys, you could arrange to run the command on a pty and
  1524.     avoid the deadlock problem.  See the chat2.pl package in the
  1525.     distributed library for ways to do this.
  1526.  
  1527.     At the risk of deadlock, it is theoretically possible to use a
  1528.     fork, two pipe calls, and an exec to manually set up the two-way
  1529.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  1530.     but this is not as portable.)  The open2 library function distributed
  1531.     with the current perl release will do this for you.
  1532.  
  1533.     It assumes it's going to talk to something like adb, both writing to
  1534.     it and reading from it.  This is presumably safe because you "know"
  1535.     that commands like adb will read a line at a time and output a line at
  1536.     a time.  Programs like sort that read their entire input stream first,
  1537.     however, are quite apt to cause deadlock.
  1538.  
  1539.  
  1540. 2.13) How can I change the first N letters of a string?
  1541.  
  1542.     Remember that the substr() function produces an lvalue, that is, it may be
  1543.     assigned to.  Therefore, to change the first character to an S, you could
  1544.     do this:
  1545.  
  1546.     substr($var,0,1) = 'S';
  1547.  
  1548.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  1549.     you should use this instead:
  1550.  
  1551.     substr($var,$[,1) = 'S';
  1552.  
  1553.     While it would be slower, you could in this case use a substitute:
  1554.  
  1555.     $var =~ s/^./S/;
  1556.     
  1557.     But this won't work if the string is empty or its first character is a
  1558.     newline, which "." will never match.  So you could use this instead:
  1559.  
  1560.     $var =~ s/^[^\0]?/S/;
  1561.  
  1562.     To do things like translation of the first part of a string, use substr,
  1563.     as in:
  1564.  
  1565.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  1566.  
  1567.     If you don't know then length of what to translate, something like
  1568.     this works:
  1569.  
  1570.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  1571.     
  1572.     For some things it's convenient to use the /e switch of the 
  1573.     substitute operator:
  1574.  
  1575.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  1576.  
  1577.     although in this case, it runs more slowly than does the previous example.
  1578.  
  1579.  
  1580. 2.14) How can I manipulate fixed-record-length files?
  1581.  
  1582.     The most efficient way is using pack and unpack.  This is faster than
  1583.     using substr.  Here is a sample chunk of code to break up and put back
  1584.     together again some fixed-format input lines, in this case, from ps.
  1585.  
  1586.     # sample input line:
  1587.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  1588.     $ps_t = 'A6 A4 A7 A5 A*';
  1589.     open(PS, "ps|");
  1590.     $_ = <PS>; print;
  1591.     while (<PS>) {
  1592.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  1593.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  1594.         print "$var: <", eval "\$$var", ">\n";
  1595.         }
  1596.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  1597.     }
  1598.  
  1599.  
  1600. 2.15) How can I make a file handle local to a subroutine?
  1601.  
  1602.     You must use the type-globbing *VAR notation.  Here is some code to
  1603.     cat an include file, calling itself recursively on nested local
  1604.     include files (i.e. those with #include "file", not #include <file>):
  1605.  
  1606.     sub cat_include {
  1607.         local($name) = @_;
  1608.         local(*FILE);
  1609.         local($_);
  1610.  
  1611.         warn "<INCLUDING $name>\n";
  1612.         if (!open (FILE, $name)) {
  1613.         warn "can't open $name: $!\n";
  1614.         return;
  1615.         }
  1616.         while (<FILE>) {
  1617.         if (/^#\s*include "([^"]*)"/) {
  1618.             &cat_include($1);
  1619.         } else {
  1620.             print;
  1621.         }
  1622.         }
  1623.         close FILE;
  1624.     }
  1625.  
  1626.  
  1627. 2.16) How can I extract just the unique elements of an array?
  1628.  
  1629.     There are several possible ways, depending on whether the
  1630.     array is ordered and you wish to preserve the ordering.
  1631.  
  1632.     a) If @in is sorted, and you want @out to be sorted:
  1633.  
  1634.     $prev = 'nonesuch';
  1635.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  1636.  
  1637.        This is nice in that it doesn't use much extra memory, 
  1638.        simulating uniq's behavior of removing only adjacent
  1639.        duplicates.
  1640.  
  1641.     b) If you don't know whether @in is sorted:
  1642.  
  1643.     undef %saw;
  1644.     @out = grep(!$saw{$_}++, @in);
  1645.  
  1646.     c) Like (b), but @in contains only small integers:
  1647.  
  1648.     @out = grep(!$saw[$_]++, @in);
  1649.  
  1650.     d) A way to do (b) without any loops or greps:
  1651.  
  1652.     undef %saw;
  1653.     @saw{@in} = ();
  1654.     @out = sort keys %saw;  # remove sort if undesired
  1655.  
  1656.     e) Like (d), but @in contains only small positive integers:
  1657.  
  1658.     undef @ary;
  1659.     @ary[@in] = @in;
  1660.     @out = sort @ary;
  1661.  
  1662.  
  1663. 2.17) How can I call alarm() or usleep() from Perl?
  1664.  
  1665.     It's available as a built-in as of version 3.038.  If you want finer
  1666.     granularity than 1 second (as usleep() provides) and have itimers and
  1667.     syscall() on your system, you can use the following.  You could also
  1668.     use select().
  1669.  
  1670.     It takes a floating-point number representing how long to delay until
  1671.     you get the SIGALRM, and returns a floating- point number representing
  1672.     how much time was left in the old timer, if any.  Note that the C
  1673.     function uses integers, but this one doesn't mind fractional numbers.
  1674.  
  1675.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  1676.     # tom christiansen <tchrist@convex.com>
  1677.     sub alarm {
  1678.     require 'syscall.ph';
  1679.     require 'sys/time.ph';
  1680.  
  1681.     local($ticks) = @_;
  1682.     local($in_timer,$out_timer);
  1683.     local($isecs, $iusecs, $secs, $usecs);
  1684.  
  1685.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  1686.  
  1687.     $secs = int($ticks);
  1688.     $usecs = ($ticks - $secs) * 1e6;
  1689.  
  1690.     $out_timer = pack($itimer_t,0,0,0,0);  
  1691.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  1692.  
  1693.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  1694.         && die "alarm: setitimer syscall failed: $!";
  1695.  
  1696.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  1697.     return $secs + ($usecs/1e6);
  1698.     }
  1699.  
  1700.  
  1701. 2.18) How can I test whether an array contains a certain element?
  1702.  
  1703.     There are several ways to approach this.  If you are going to make
  1704.     this query many times and the values are arbitrary strings, the
  1705.     fastest way is probably to invert the original array and keep an
  1706.     associative array lying about whose keys are the first array's values.
  1707.  
  1708.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  1709.     undef %is_blue;
  1710.     for (@blues) { $is_blue{$_} = 1; }
  1711.  
  1712.     Now you can check whether $is_blue{$some_color}.  It might have been
  1713.     a good idea to keep the blues all in an assoc array in the first place.
  1714.  
  1715.     If the values are all small integers, you could use a simple
  1716.     indexed array.  This kind of an array will take up less space:
  1717.  
  1718.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  1719.     undef @is_tiny_prime;
  1720.     for (@primes) { $is_tiny_prime[$_] = 1; }
  1721.  
  1722.     Now you check whether $is_tiny_prime[$some_number].
  1723.  
  1724.     If the values in question are integers, but instead of strings,
  1725.     you can save quite a lot of space by using bit strings instead:
  1726.  
  1727.     @articles = ( 1..10, 150..2000, 2017 );
  1728.     undef $read;
  1729.     grep (vec($read,$_,1) = 1, @articles);
  1730.     
  1731.     Now check whether vec($read,$n,1) is true for some $n.
  1732.  
  1733.  
  1734. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  1735.  
  1736.     Perl's exception-handling mechanism is its eval operator.  You 
  1737.     can use eval as setjmp and die as longjmp.  Here's an example
  1738.     of Larry's for timed-out input, which in C is often implemented
  1739.     using setjmp and longjmp:
  1740.  
  1741.       $SIG{ALRM} = TIMEOUT;
  1742.       sub TIMEOUT { die "restart input\n" }
  1743.  
  1744.       do { eval { &realcode } } while $@ =~ /^restart input/;
  1745.  
  1746.       sub realcode {
  1747.           alarm 15;
  1748.           $ans = <STDIN>;
  1749.           alarm 0;
  1750.       }
  1751.  
  1752.    Here's an example of Tom's for doing atexit() handling:
  1753.  
  1754.     sub atexit { push(@_exit_subs, @_) }
  1755.  
  1756.     sub _cleanup { unlink $tmp }
  1757.  
  1758.     &atexit('_cleanup');
  1759.  
  1760.     eval <<'End_Of_Eval';  $here = __LINE__;
  1761.     # as much code here as you want
  1762.     End_Of_Eval
  1763.  
  1764.     $oops = $@;  # save error message
  1765.  
  1766.     # now call his stuff
  1767.     for (@_exit_subs) { &$_() }
  1768.  
  1769.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  1770.         " line " . ($1+$here)/e, die $oops);
  1771.  
  1772.     You can register your own routines via the &atexit function now.  You
  1773.     might also want to use the &realcode method of Larry's rather than
  1774.     embedding all your code in the here-is document.  Make sure to leave
  1775.     via die rather than exit, or write your own &exit routine and call
  1776.     that instead.   In general, it's better for nested routines to exit
  1777.     via die rather than exit for just this reason.
  1778.  
  1779.     Eval is also quite useful for testing for system dependent features,
  1780.     like symlinks, or using a user-input regexp that might otherwise
  1781.     blowup on you.
  1782.  
  1783.  
  1784. 2.20) Why doesn't Perl interpret my octal data octally?
  1785.  
  1786.     Perl only understands octal and hex numbers as such when they occur
  1787.     as constants in your program.  If they are read in from somewhere
  1788.     and assigned, then no automatic conversion takes place.  You must
  1789.     explicitly use oct() or hex() if you want this kind of thing to happen.
  1790.     Actually, oct() knows to interpret both hex and octal numbers, while
  1791.     hex only converts hexadecimal ones.  For example:
  1792.  
  1793.     {
  1794.         print "What mode would you like? ";
  1795.         $mode = <STDIN>;
  1796.         $mode = oct($mode);
  1797.         unless ($mode) {
  1798.         print "You can't really want mode 0!\n";
  1799.         redo;
  1800.         } 
  1801.         chmod $mode, $file;
  1802.     } 
  1803.  
  1804.     Without the octal conversion, a requested mode of 755 would turn 
  1805.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  1806.  
  1807.     If you want something that handles decimal, octal and hex input, 
  1808.     you could follow the suggestion in the man page and use:
  1809.  
  1810.     $val = oct($val) if $val =~ /^0/;
  1811.  
  1812. 2.21) How do I sort an associative array by value instead of by key?
  1813.  
  1814.     You have to declare a sort subroutine to do this.  Let's assume
  1815.     you want an ASCII sort on the values of the associative array %ary.
  1816.     You could do so this way:
  1817.  
  1818.     foreach $key (sort by_value keys %ary) {
  1819.         print $key, '=', $ary{$key}, "\n";
  1820.     } 
  1821.     sub by_value { $ary{$a} cmp $ary{$b}; }
  1822.  
  1823.     If you wanted a descending numeric sort, you could do this:
  1824.  
  1825.     sub by_value { $ary{$b} <=> $ary{$a}; }
  1826.  
  1827.     You can also inline your sort function, like this:
  1828.  
  1829.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  1830.         print $key, '=', $ary{$key}, "\n";
  1831.     } 
  1832.  
  1833.     If you wanted a function that didn't have the array name hard-wired
  1834.     into it, you could so this:
  1835.  
  1836.     foreach $key (&sort_by_value(*ary)) {
  1837.         print $key, '=', $ary{$key}, "\n";
  1838.     } 
  1839.     sub sort_by_value {
  1840.         local(*x) = @_;
  1841.         sub _by_value { $x{$a} cmp $x{$b}; } 
  1842.         sort _by_value keys %x;
  1843.     } 
  1844.  
  1845.     If you want neither an alphabetic nor a numeric sort, then you'll 
  1846.     have to code in your own logic instead of relying on the built-in
  1847.     signed comparison operators "cmp" and "<=>".
  1848.  
  1849.     Note that if you're sorting on just a part of the value, such as a
  1850.     piece you might extract via split, unpack, pattern-matching, or
  1851.     substr, then rather than performing that operation inside your sort
  1852.     routine on each call to it, it is significantly more efficient to
  1853.     build a parallel array of just those portions you're sorting on, sort
  1854.     the indices of this parallel array, and then to subscript your original
  1855.     array using the newly sorted indices.  This method works on both
  1856.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  1857.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  1858.     Computable Field" for a simple example of this.
  1859.  
  1860.  
  1861. 2.22) How can I capture STDERR from an external command?
  1862.  
  1863.     There are three basic ways of running external commands:
  1864.  
  1865.     system $cmd;
  1866.     $output = `$cmd`;
  1867.     open (PIPE, "cmd |");
  1868.  
  1869.     In the first case, both STDOUT and STDERR will go the same place as
  1870.     the script's versions of these, unless redirected.  You can always put
  1871.     them where you want them and then read them back when the system
  1872.     returns.  In the second and third cases, you are reading the STDOUT
  1873.     *only* of your command.  If you would like to have merged STDOUT and
  1874.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  1875.     STDOUT:
  1876.  
  1877.     $output = `$cmd 2>&1`;
  1878.     open (PIPE, "cmd 2>&1 |");
  1879.  
  1880.     Another possibility is to run STDERR into a file and read the file 
  1881.     later, as in 
  1882.  
  1883.     $output = `$cmd 2>some_file`;
  1884.     open (PIPE, "cmd 2>some_file |");
  1885.     
  1886.     Here's a way to read from both of them and know which descriptor
  1887.     you got each line from.  The trick is to pipe only STDERR through
  1888.     sed, which then marks each of its lines, and then sends that
  1889.     back into a merged STDOUT/STDERR stream, from which your Perl program
  1890.     then reads a line at a time:
  1891.  
  1892.         open (CMD, 
  1893.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  1894.  
  1895.         while (<CMD>) {
  1896.           if (s/^STDERR://)  {
  1897.               print "line from stderr: ", $_;
  1898.           } else {
  1899.               print "line from stdout: ", $_;
  1900.           }
  1901.         }
  1902.  
  1903.     Be apprised that you *must* use Bourne shell redirection syntax
  1904.     here, not csh!  In fact, you can't even do these things with csh.
  1905.     For details on how lucky you are that perl's system() and backtick
  1906.     and pipe opens all use Bourne shell, fetch the file from convex.com
  1907.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  1908.     interface is the Bourne shell.
  1909.  
  1910.  
  1911. 2.23) Why doesn't open return an error when a pipe open fails?
  1912.  
  1913.     These statements:
  1914.  
  1915.     open(TOPIPE, "|bogus_command") || die ...
  1916.     open(FROMPIPE, "bogus_command|") || die ...
  1917.  
  1918.     will not fail just for lack of the bogus_command.  They'll only
  1919.     fail if the fork to run them fails, which is seldom the problem.
  1920.  
  1921.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  1922.     exits prematurely or doesn't run.  If you are reading from the
  1923.     FROMPIPE, you need to check the close() to see what happened.
  1924.  
  1925.     If you want an answer sooner than pipe buffering might otherwise
  1926.     afford you, you can do something like this:
  1927.  
  1928.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  1929.     (kill 0, $kid) || die "bogus_command failed";
  1930.  
  1931.     This works fine if bogus_command doesn't have shell metas in it, but
  1932.     if it does, the shell may well not have exited before the kill 0.  You
  1933.     could always introduce a delay:
  1934.  
  1935.     $kid = open (PIPE, "bogus_command </dev/null |");
  1936.     sleep 1;
  1937.     (kill 0, $kid) || die "bogus_command failed";
  1938.  
  1939.     but this is sometimes undesirable, and in any event does not guarantee
  1940.     correct behavior.  But it seems slightly better than nothing.
  1941.  
  1942.     Similar tricks can be played with writable pipes if you don't wish to
  1943.     catch the SIGPIPE.
  1944.  
  1945.  
  1946. 2.24) How can I compare two date strings?
  1947.  
  1948.     If the dates are in an easily parsed, predetermined format, then you
  1949.     can break them up into their component parts and call &timelocal from
  1950.     the distributed perl library.  If the date strings are in arbitrary
  1951.     formats, however, it's probably easier to use the getdate program
  1952.     from the Cnews distribution, since it accepts a wide variety of dates.
  1953.     Note that in either case the return values you will really be
  1954.     comparing will be the total time in seconds as return by time().
  1955.    
  1956.     Here's a getdate function for perl that's not very efficient; you 
  1957.     can do better this by sending it many dates at once or modifying
  1958.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1959.  
  1960.     sub getdate {
  1961.         local($_) = shift;
  1962.  
  1963.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  1964.         # getdate has broken timezone sign reversal!
  1965.  
  1966.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1967.         chop;
  1968.         $_;
  1969.     } 
  1970.  
  1971.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1972.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1973.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1974.     mail for details.
  1975.  
  1976.  
  1977. 2.25) What's the fastest way to code up a given task in perl?
  1978.  
  1979.     Because Perl so lends itself to a variety of different approaches
  1980.     for any given task, a common question is which is the fastest way
  1981.     to code a given task.  Since some approaches can be dramatically
  1982.     more efficient that others, it's sometimes worth knowing which is
  1983.     best.  Unfortunately, the implementation that first comes to mind,
  1984.     perhaps as a direct translation from C or the shell, often yields
  1985.     suboptimal performance.  Not all approaches have the same results
  1986.     across different hardware and software platforms.  Furthermore,
  1987.     legibility must sometimes be sacrificed for speed.
  1988.  
  1989.     While an experienced perl programmer can sometimes eye-ball the code
  1990.     and make an educated guess regarding which way would be fastest,
  1991.     surprises can still occur.  So, in the spirit of perl programming
  1992.     being an empirical science, the best way to find out which of several
  1993.     different methods runs the fastest is simply to code them all up and
  1994.     time them. For example:
  1995.  
  1996.     $COUNT = 10_000; $| = 1;
  1997.  
  1998.     print "method 1: ";
  1999.  
  2000.         ($u, $s) = times;
  2001.         for ($i = 0; $i < $COUNT; $i++) {
  2002.         # code for method 1
  2003.         }
  2004.         ($nu, $ns) = times;
  2005.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  2006.  
  2007.     print "method 2: ";
  2008.  
  2009.         ($u, $s) = times;
  2010.         for ($i = 0; $i < $COUNT; $i++) {
  2011.         # code for method 2
  2012.         }
  2013.         ($nu, $ns) = times;
  2014.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  2015.  
  2016.     For more specific tips, see the section on Efficiency in the
  2017.     ``Other Oddments'' chapter at the end of the Camel Book.
  2018.  
  2019.  
  2020. 2.26) How can I know how many entries are in an associative array?
  2021.  
  2022.     While the number of elements in a @foobar array is simply @foobar when
  2023.     used in a scalar, you can't figure out how many elements are in an
  2024.     associative array in an analogous fashion.  That's because %foobar in
  2025.     a scalar context returns the ratio (as a string) of number of buckets
  2026.     filled versus the number allocated.  For example, scalar(%ENV) might
  2027.     return "20/32".  While perl could in theory keep a count, this would
  2028.     break down on associative arrays that have been bound to dbm files.
  2029.  
  2030.     However, while you can't get a count this way, one thing you *can* use
  2031.     it for is to determine whether there are any elements whatsoever in
  2032.     the array, since "if (%table)" is guaranteed to be false if nothing
  2033.     has ever been stored in it.  
  2034.  
  2035.     So you either have to keep your own count around and increments
  2036.     it every time you store a new key in the array, or else do it
  2037.     on the fly when you really care, perhaps like this:
  2038.  
  2039.     $count++ while each %ENV;
  2040.  
  2041.     This preceding method will be faster than extracting the
  2042.     keys into a temporary array to count them.
  2043.  
  2044.     As of a very recent patch, you can say
  2045.  
  2046.     $count = keys %ENV;
  2047.  
  2048.  
  2049.  
  2050. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  2051.  
  2052.     Because some stdio's set error and eof flags that need clearing.
  2053.  
  2054.     Try keeping around the seekpointer and go there, like this:
  2055.      $where = tell(LOG);
  2056.      seek(LOG, $where, 0);
  2057.  
  2058.     If that doesn't work, try seeking to a different part of the file and
  2059.     then back.  If that doesn't work, try seeking to a different part of
  2060.     the file, reading something, and then seeking back.  If that doesn't
  2061.     work, give up on your stdio package and use sysread.  You can't call
  2062.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  2063.     handler, you're out of luck.  Best to just use sysread() from the
  2064.     start for the tty.
  2065.  
  2066.  
  2067. 2.28) Do I always/never have to quote my strings or use semicolons?
  2068.  
  2069.     You don't have to quote strings that can't mean anything else
  2070.     in the language, like identifiers with any upper-case letters
  2071.     in them.  Therefore, it's fine to do this:
  2072.  
  2073.     $SIG{INT} = Timeout_Routine;
  2074.     or 
  2075.  
  2076.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  2077.  
  2078.     but you can't get away with this:
  2079.  
  2080.     $foo{while} = until;
  2081.  
  2082.     in place of 
  2083.  
  2084.     $foo{'while'} = 'until';
  2085.  
  2086.     The requirements on semicolons have been increasingly relaxed.  You no
  2087.     longer need one at the end of a block, but stylistically, you're
  2088.     better to use them if you don't put the curly brace on the same line:
  2089.  
  2090.     for (1..10) { print }
  2091.  
  2092.     is ok, as is
  2093.  
  2094.     @nlist = sort { $a <=> $b } @olist;
  2095.  
  2096.     but you probably shouldn't do this:
  2097.     
  2098.     for ($i = 0; $i < @a; $i++) {
  2099.         print "i is $i\n"  # <-- oops!
  2100.     } 
  2101.  
  2102.     because you might want to add lines later, and anyway, 
  2103.     it looks funny. :-)
  2104.  
  2105.  
  2106. 2.29) How can I translate tildes in a filename?
  2107.  
  2108.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  2109.     The classic request is to be able to do something like:
  2110.  
  2111.     open(FILE, "~/dir1/file1");
  2112.     open(FILE, "~tchrist/dir1/file1");
  2113.  
  2114.     which doesn't work.  (And you don't know it, because you 
  2115.     did a system call without an "|| die" clause! :-)
  2116.  
  2117.     If you *know* you're on a system with the csh, and you *know*
  2118.     that Larry hasn't internalized file globbing, then you could
  2119.     get away with 
  2120.  
  2121.     $filename = <~tchrist/dir1/file1>;
  2122.  
  2123.     but that's pretty iffy.
  2124.  
  2125.     A better way is to do the translation yourself, as in:
  2126.  
  2127.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  2128.  
  2129.     More robust and efficient versions that checked for error conditions,
  2130.     handed simple ~/blah notation, and cached lookups are all reasonable
  2131.     enhancements.
  2132.  
  2133.  
  2134. 2.30) How can I convert my shell script to Perl?
  2135.  
  2136.     Larry's standard answer for this is to send your script to me (Tom
  2137.     Christiansen) with appropriate supplications and offerings.  :-(
  2138.     That's because there's no automatic machine translator.  Even if you
  2139.     were, you wouldn't gain a lot, as most of the external programs would
  2140.     still get called.  It's the same problem as blind translation into C:
  2141.     you're still apt to be bogged down by exec()s.  You have to analyze
  2142.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  2143.     not uncommon to see one, two, or even three orders of magnitude of
  2144.     speed difference between the brute-force and the recoded approaches.
  2145.  
  2146.  
  2147. 2.31) What is variable suicide and how can I prevent it?
  2148.  
  2149.     Variable suicide is a nasty sideeffect of dynamic scoping and
  2150.     the way variables are passed by reference.  If you say
  2151.  
  2152.     $x = 17;
  2153.     &munge($x);
  2154.     sub munge {
  2155.         local($x);
  2156.         local($myvar) = $_[0];
  2157.         ...
  2158.     } 
  2159.  
  2160.     Then you have just clubbered $_[0]!  Why this is occurring 
  2161.     is pretty heavy wizardry: the reference to $x stored in 
  2162.     $_[0] was temporarily occluded by the previous local($x)
  2163.     statement (which, you're recall, occurs at run-time, not
  2164.     compile-time).  The work around is simple, however: declare
  2165.     your formal parameters first:
  2166.  
  2167.     sub munge {
  2168.         local($myvar) = $_[0];
  2169.         local($x);
  2170.         ...
  2171.     }
  2172.  
  2173.     That doesn't help you if you're going to be trying to access
  2174.     @_ directly after the local()s.  In this case, careful use
  2175.     of the package facility is your only recourse.
  2176.  
  2177.     Another manifestation of this problem occurs due to the
  2178.     magical nature of the index variable in a foreach() loop.
  2179.  
  2180.     @num = 0 .. 4;
  2181.     print "num begin  @num\n";
  2182.     foreach $m (@num) { &ug }
  2183.     print "num finish @num\n";
  2184.     sub ug {
  2185.         local($m) = 42;
  2186.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  2187.     }
  2188.     
  2189.     Which prints out the mysterious:
  2190.  
  2191.     num begin  0 1 2 3 4
  2192.     m=42  42,1,2,3
  2193.     m=42  0,42,2,3
  2194.     m=42  0,1,42,3
  2195.     m=42  0,1,2,42
  2196.     m=42  0,1,2,3
  2197.     num finish 0 1 2 3 4
  2198.  
  2199.     What's happening here is that $m is an alias for each 
  2200.     element of @num.  Inside &ug, you temporarily change
  2201.     $m.  Well, that means that you've also temporarily 
  2202.     changed whatever $m is an alias to!!  The only workaround
  2203.     is to be careful with global variables, using packages,
  2204.     and/or just be aware of this potential in foreach() loops.
  2205.  
  2206.  
  2207. 2.32) Can I use Perl regular expressions to match balanced text?
  2208.  
  2209.     No, or at least, not by the themselves.
  2210.  
  2211.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  2212.     strictly regular because they do backtracking (the \1 notation), you
  2213.     still can't do it.  You need to employ auxiliary logic.  A simple
  2214.     approach would involve keeping a bit of state around, something 
  2215.     vaguely like this (although we don't handle patterns on the same line):
  2216.  
  2217.     while(<>) {
  2218.         if (/pat1/) {
  2219.         if ($inpat++ > 0) { warn "already saw pat1" } 
  2220.         redo;
  2221.         } 
  2222.         if (/pat2/) {
  2223.         if (--$inpat < 0) { warn "never saw pat1" } 
  2224.         redo;
  2225.         } 
  2226.     }
  2227.  
  2228.     A rather more elaborate subroutine to pull out balanced and possibly
  2229.     nested single chars, like ` and ', { and }, or ( and ) can be found
  2230.     on convex.com in /pub/perl/scripts/pull_quotes.
  2231.  
  2232.  
  2233. 2.33) Can I use Perl to run a telnet or ftp session?
  2234.  
  2235.     Sure, you can connect directly to them using sockets, or you can run a
  2236.     session on a pty.  In either case, Randal's chat2 package, which is
  2237.     distributed with the perl source, will come in handly.  It address
  2238.     much the same problem space as Don Libes's expect package does.  Two
  2239.     examples of using managing an ftp session using chat2 can be found on
  2240.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  2241.  
  2242.     Caveat lector: chat2 is documented only by example, may not run on
  2243.     System V systems, and is subtly machine dependent both in its ideas
  2244.     of networking and in pseudottys.
  2245.  
  2246.  
  2247. 2.34) What does "Malformed command links" mean?
  2248.  
  2249.     This is a bug in 4.035.  While in general it's merely a cosmetic
  2250.     problem, it often comanifests with a highly undesirable coredumping
  2251.     problem.  Programs known to be affected by the fatal coredump include
  2252.     plum and pcops.  Since perl5 is pretty much a total rewrite, we can
  2253.     count on it being fixed then, but if anyone tracks down the coredump
  2254.     problem before then, a significant portion of the Perl world would
  2255.     rejoice.
  2256.  
  2257.  
  2258. 2.35) How can I set up a footer format to be used with write()?
  2259.  
  2260.     While the $^ variable contains the name of the current header format,
  2261.     there is no corresponding mechanism to automatically do the same thing
  2262.     for a footer.  Not knowing how big a format is going to be until you
  2263.     evaluate it is one of the major problems.
  2264.  
  2265.     If you have a fixed-size footer, you can get footers by checking for
  2266.     line left on page ($-) before each write, and printing the footer
  2267.     yourself if necessary.
  2268.  
  2269.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  2270.     and always write()ing to the KID, who then postprocesses its STDIN to
  2271.     rearrange headers and footers however you like.  Not very convenient,
  2272.     but doable.
  2273.  
  2274.  
  2275. 2.36) Why does my Perl program keep growing in size?
  2276.  
  2277.     While there may be a real memory leak in the Perl source code or even
  2278.     whichever malloc() you're using, common causes are incomplete eval()s
  2279.     or local()s in loops.
  2280.  
  2281.     An eval() which terminates in error due to a failed parsing 
  2282.     will leave a bit of memory unusable.
  2283.  
  2284.     A local() inside a loop:
  2285.  
  2286.     for (1..100) {
  2287.         local(@array);
  2288.     } 
  2289.  
  2290.     will build up 100 versions of @array before the loop is done.
  2291.     The work-around is:
  2292.  
  2293.     local(@array);
  2294.     for (1..100) {
  2295.         undef @array;
  2296.     } 
  2297.  
  2298.     Larry reports that this behavior is fixed for perl5.
  2299.  
  2300. print "Just another Perl hacker,"
  2301. -- 
  2302. Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
  2303. merlyn@ora.com (semi-permanent) merlyn@kandinsky.intel.com (NEWSREADING ONLY)
  2304. Quote: "Welcome to Portland, Oregon, home of the California Raisins!"
  2305. e California Raisins!"
  2306.